﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Services.Protocols;

namespace Agile.Engine.Service
{
    public interface IClientServiceProxy
    {
        /// <summary>
        /// 服务地址
        /// </summary>
        string Uri { get; set; }
        /// <summary>
        /// 服务代理
        /// </summary>
        IWebServiceProxy WebServiceProxy { get; set; }
        /// <summary>
        /// 调用服务
        /// </summary>
        /// <param name="args">服务参数</param>
        /// <returns></returns>
        string InvokeService(string args, Action<IAsyncResult> callback);
    }

    public class ClientServiceProxy : IClientServiceProxy
    {
        public ClientServiceProxy(string Uri, int Timeout)
        {
            InitializeSoapClient(Uri, Timeout);
        }

        private ClientServiceProxy()
        {

        }

        /// <summary>
        /// 服务定位地址
        /// </summary>
        public string Uri { get; set; }
        public int Timeout { get; set; }

        /// <summary>
        /// 服务代理
        /// </summary>
        public IWebServiceProxy WebServiceProxy { get; set; }

        /// <summary>
        /// 客户端服务协议
        /// </summary>
        protected SoapHttpClientProtocol soapClient
        {
            get { return WebServiceProxy as SoapHttpClientProtocol; }
        }

        /// <summary>
        /// 调用服务
        /// </summary>
        /// <param name="args">参数</param>
        /// <param name="callback">回调方法</param>
        /// <returns></returns>
        public string InvokeService(string args, Action<IAsyncResult> callback)
        {
            if (WebServiceProxy == null)
            {
                InitializeSoapClient(Uri, Timeout);
            }

            Func<string, string> asynInvoke = WebServiceProxy.InvokeService;
            var ar = asynInvoke.BeginInvoke(args, new AsyncCallback(callback), null);
            return asynInvoke.EndInvoke(ar);
        }

        private void InitializeSoapClient(string uri, int timeout)
        {
            var wpf = new Spring.Web.Services.WebServiceProxyFactory();
            wpf.ServiceInterface = typeof(Agile.Engine.Service.IWebServiceProxy);
            wpf.ServiceUri = new Spring.Core.IO.UrlResource(uri);

            SoapHttpClientProtocol client = wpf.GetObject() as SoapHttpClientProtocol;
            client.Timeout = timeout; //60000=10分钟超时
            WebServiceProxy = (client as Agile.Engine.Service.IWebServiceProxy);
        }
    }
}
